package com.idanchuang.component.webflux.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.idanchuang.component.webflux.dto.LoginSsoUserDTO;
import com.idanchuang.component.webflux.dto.LoginUserDTO;
import com.zoi7.component.core.base.BaseClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;

import java.net.URLDecoder;

/**
 * request工具类
 */
public class RequestUtils extends BaseClass {

    private static final Logger log = LoggerFactory.getLogger(RequestUtils.class);

    /**
     * @return 当前登入用户信息 (来源为gateway透传)
     */
    public static JSONObject getUserJsonObject(HttpRequest request) {
        String userinfo = getUserJsonString(request);
        return notBlank(userinfo) ? JSON.parseObject(userinfo) : null;
    }

    /**
     * @return 当前登入用户信息 (来源为gateway透传)
     */
    public static LoginUserDTO getUserDTO(HttpRequest request) {
        String userinfo = getUserJsonString(request);
        return notBlank(userinfo) ? JSON.parseObject(userinfo, LoginUserDTO.class) : null;
    }

    /**
     * @return 当前登入用户信息 (来源为gateway透传)
     */
    public static String getUserJsonString(HttpRequest request) {
        try {
            String headerName = "userinfo";
            String originUserinfo = request.getHeaders().getFirst(headerName);
            if (notBlank(originUserinfo)) {
                return URLDecoder.decode(originUserinfo, "UTF-8");
            }
        } catch (Exception e) {
            log.error("getCurrentUser failed", e);
        }
        return null;
    }

    /**
     * @return 当前登入后台用户信息 (来源为gateway透传)
     */
    public static JSONObject getSsoUserJsonObject(HttpRequest request) {
        String userinfo = getSsoUserJsonString(request);
        return notBlank(userinfo) ? JSON.parseObject(userinfo) : null;
    }

    /**
     * @return 当前登入后台用户信息 (来源为gateway透传)
     */
    public static LoginSsoUserDTO getSsoUserDTO(HttpRequest request) {
        String userinfo = getSsoUserJsonString(request);
        return notBlank(userinfo) ? JSON.parseObject(userinfo, LoginSsoUserDTO.class) : null;
    }

    /**
     * @return 当前登入后台用户信息 (来源为gateway透传)
     */
    public static String getSsoUserJsonString(HttpRequest request) {
        try {
            String headerName = "userinfo";
            String originUserinfo = request.getHeaders().getFirst(headerName);
            if (notBlank(originUserinfo)) {
                return URLDecoder.decode(originUserinfo, "UTF-8");
            }
        } catch (Exception e) {
            log.error("getSsoUserJsonString failed", e);
        }
        return null;
    }

}
